package com.captainbank.tcl.tclapplication.ui.activity.function;

import android.content.res.Configuration;
import android.hardware.Camera;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.captainbank.tcl.tclapplication.R;
import com.captainbank.tcl.tclapplication.ui.activity.basic.BaseActivity;
import com.captainbank.tcl.tclapplication.utils.MyToast;
import com.captainbank.tcl.tclapplication.utils.SharePreferenceManager;
import com.captainbank.tcl.tclapplication.utils.StringUtil;
import com.github.faucamp.simplertmp.RtmpHandler;
import com.seu.magicfilter.utils.MagicFilterType;

import net.ossrs.yasea.SrsCameraView;
import net.ossrs.yasea.SrsEncodeHandler;
import net.ossrs.yasea.SrsPublisher;
import net.ossrs.yasea.SrsRecordHandler;

import java.io.IOException;
import java.net.SocketException;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by TCL on 2019/5/24.
 * Describe:
 */
public class LiveActivity extends BaseActivity implements RtmpHandler.RtmpListener,
        SrsRecordHandler.SrsRecordListener, SrsEncodeHandler.SrsEncodeListener {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.glsurfaceview_camera)
    SrsCameraView glsurfaceviewCamera;
    @BindView(R.id.btn_push)
    Button btnPush;
    @BindView(R.id.btn_code)
    Button btnCode;
    @BindView(R.id.tv_url)
    TextView tvUrl;

    private static final String TAG = "LiveActivity";
    private String rtmpUrl = "rtmp://ossrs.net/" + getRandomAlphaString(3) + '/' + getRandomAlphaDigitString(5);
    private SrsPublisher mPublisher;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_live;
    }

    @Override
    protected void initData() {
        SharePreferenceManager.init(LiveActivity.this, SharePreferenceManager.Live);
        String rtmpUrlTemp = SharePreferenceManager.getLiveRtmpurl();
        if (StringUtil.checkIsNotNull(rtmpUrlTemp)) {
            rtmpUrl = rtmpUrlTemp;
        }
        System.out.println("输出推流地址：" + rtmpUrl);
        tvUrl.setText(rtmpUrl);
    }

    @Override
    protected void initView() {
        toolbar.setTitle(getString(R.string.title_live));
        toolbar.inflateMenu(R.menu.menu_filter);
        //初始化
        mPublisher = new SrsPublisher(glsurfaceviewCamera);
        mPublisher.setEncodeHandler(new SrsEncodeHandler(this));
        mPublisher.setRtmpHandler(new RtmpHandler(this));
        mPublisher.setRecordHandler(new SrsRecordHandler(this));
        mPublisher.setPreviewResolution(640, 360);
        mPublisher.setOutputResolution(360, 640);
        mPublisher.setVideoHDMode();
        mPublisher.startCamera();

        glsurfaceviewCamera.setCameraCallbacksHandler(new SrsCameraView.CameraCallbacksHandler() {
            @Override
            public void onCameraParameters(Camera.Parameters params) {
                //params.setFocusMode("custom-focus");
                //params.setWhiteBalance("custom-balance");
                //etc...
            }
        });
    }

    @Override
    protected void setListener() {
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int id = item.getItemId();
                if(id==R.id.toolbar_menu){
                    return true;
                }else{
                    MagicFilterType magicFilterType;
                    switch (id) {
                        case R.id.toolbar_beauty:
                            magicFilterType = MagicFilterType.BEAUTY;
                            break;
                        case R.id.toolbar_cool:
                            magicFilterType = MagicFilterType.COOL;
                            break;
                        case R.id.toolbar_early_bird:
                            magicFilterType = MagicFilterType.EARLYBIRD;
                            break;
                        case R.id.toolbar_evergreen:
                            magicFilterType = MagicFilterType.EVERGREEN;
                            break;
                        case R.id.toolbar_n1977:
                            magicFilterType = MagicFilterType.N1977;
                            break;
                        case R.id.toolbar_nostalgia:
                            magicFilterType = MagicFilterType.NOSTALGIA;
                            break;
                        case R.id.toolbar_romance:
                            magicFilterType = MagicFilterType.ROMANCE;
                            break;
                        case R.id.toolbar_sunrise:
                            magicFilterType = MagicFilterType.SUNRISE;
                            break;
                        case R.id.toolbar_sunset:
                            magicFilterType = MagicFilterType.SUNSET;
                            break;
                        case R.id.toolbar_warm:
                            magicFilterType = MagicFilterType.WARM;
                            break;
                        case R.id.toolbar_tender:
                            magicFilterType = MagicFilterType.TENDER;
                            break;
                        case R.id.toolbar_toast:
                            magicFilterType = MagicFilterType.TOASTER2;
                            break;
                        case R.id.toolbar_valencia:
                            magicFilterType = MagicFilterType.VALENCIA;
                            break;
                        case R.id.toolbar_walden:
                            magicFilterType = MagicFilterType.WALDEN;
                            break;
                        case R.id.toolbar_original:
                        default:
                            magicFilterType = MagicFilterType.NONE;
                            break;
                    }
                    mPublisher.switchCameraFilter(magicFilterType);
                    return true;
                }
            }
        });
    }

    @OnClick({R.id.btn_push, R.id.btn_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_push:
                if (btnPush.getText().toString().contentEquals("推流")) {
                    rtmpUrl = tvUrl.getText().toString().trim();
                    SharePreferenceManager.setLiveRtmpurl(rtmpUrl);

                    mPublisher.startPublish(rtmpUrl);
                    mPublisher.startCamera();

                    if (btnCode.getText().toString().contentEquals("软编码")) {
                        showToast("Use hard encoder");
                    } else {
                        showToast("Use soft encoder");
                    }
                    btnPush.setText("暂停");
                    btnCode.setEnabled(false);
//                    btnPause.setEnabled(true);
                } else if (btnPush.getText().toString().contentEquals("暂停")) {
                    mPublisher.stopPublish();
                    mPublisher.stopRecord();
                    btnPush.setText("推流");
//                    btnRecord.setText("record");
                    btnCode.setEnabled(true);
//                    btnPause.setEnabled(false);
                }
                break;
            case R.id.btn_code:
                if (btnCode.getText().toString().contentEquals("软编码")) {
                    mPublisher.switchToSoftEncoder();
                    btnCode.setText("硬编码");
                } else if (btnCode.getText().toString().contentEquals("硬编码")) {
                    mPublisher.switchToHardEncoder();
                    btnCode.setText("软编码");
                }
                break;
        }
    }

    private static String getRandomAlphaString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    private static String getRandomAlphaDigitString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mPublisher.getCamera() == null) {
            //if the camera was busy and available again
            mPublisher.startCamera();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        final Button btn = (Button) findViewById(R.id.btn_push);
        btn.setEnabled(true);
        mPublisher.resumeRecord();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPublisher.pauseRecord();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPublisher.stopPublish();
        mPublisher.stopRecord();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
//        mPublisher.stopEncode();
//        mPublisher.stopRecord();
//        btnRecord.setText("record");
//        mPublisher.setScreenOrientation(newConfig.orientation);
//        if (btnPublish.getText().toString().contentEquals("stop")) {
//            mPublisher.startEncode();
//        }
//        mPublisher.startCamera();
    }

    @Override
    public void onRtmpConnecting(String msg) {
        showToast(msg);
    }

    @Override
    public void onRtmpConnected(String msg) {
        showToast(msg);
    }

    @Override
    public void onRtmpVideoStreaming() {
    }

    @Override
    public void onRtmpAudioStreaming() {
    }

    @Override
    public void onRtmpStopped() {
        showToast("Stopped");
    }

    @Override
    public void onRtmpDisconnected() {
        showToast("Disconnected");
    }

    @Override
    public void onRtmpVideoFpsChanged(double fps) {
        Log.i(TAG, String.format("Output Fps: %f", fps));
    }

    @Override
    public void onRtmpVideoBitrateChanged(double bitrate) {
        int rate = (int) bitrate;
        if (rate / 1000 > 0) {
            Log.i(TAG, String.format("Video bitrate: %f kbps", bitrate / 1000));
        } else {
            Log.i(TAG, String.format("Video bitrate: %d bps", rate));
        }
    }

    @Override
    public void onRtmpAudioBitrateChanged(double bitrate) {
        int rate = (int) bitrate;
        if (rate / 1000 > 0) {
            Log.i(TAG, String.format("Audio bitrate: %f kbps", bitrate / 1000));
        } else {
            Log.i(TAG, String.format("Audio bitrate: %d bps", rate));
        }
    }

    @Override
    public void onRtmpSocketException(SocketException e) {
        handleException(e);
    }

    @Override
    public void onRtmpIOException(IOException e) {
        handleException(e);
    }

    @Override
    public void onRtmpIllegalArgumentException(IllegalArgumentException e) {
        handleException(e);
    }

    @Override
    public void onRtmpIllegalStateException(IllegalStateException e) {
        handleException(e);
    }

    @Override
    public void onRecordPause() {
        showToast("Record paused");
    }

    @Override
    public void onRecordResume() {
        showToast("Record resumed");
    }

    @Override
    public void onRecordStarted(String msg) {
        showToast("Recording file: " + msg);
    }

    @Override
    public void onRecordFinished(String msg) {
        showToast("MP4 file saved: " + msg);
    }

    @Override
    public void onRecordIOException(IOException e) {
        handleException(e);
    }

    @Override
    public void onRecordIllegalArgumentException(IllegalArgumentException e) {
        handleException(e);
    }

    @Override
    public void onNetworkWeak() {
        showToast("Network weak");
    }

    @Override
    public void onNetworkResume() {
        showToast("Network resume");
    }

    @Override
    public void onEncodeIllegalArgumentException(IllegalArgumentException e) {
        handleException(e);
    }

    private void handleException(Exception e) {
        try {
            MyToast.toastNormal(LiveActivity.this, e.getMessage());
            mPublisher.stopPublish();
            mPublisher.stopRecord();
//            btnPublish.setText("publish");
//            btnRecord.setText("record");
//            btnSwitchEncoder.setEnabled(true);
        } catch (Exception e1) {
            //
        }
    }

    private void showToast(String msg) {
        MyToast.toastNormal(LiveActivity.this, msg);
    }

}
